package com.bailong.nanny.controller;

import sun.java2d.pipe.DrawImage;

import javax.imageio.ImageIO;
import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.IOException;
@WebServlet(name = "/code.do",urlPatterns = "/code.do")
public class CodeServlet extends HttpServlet {
    private static final int WIDTH=60;
    private static final int HEIGHT=30;
    private static final int FONT_SIZE=20;
    private StringBuffer codeStr = null;
    private String[]str = new String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n",
            "o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建内存图片
        BufferedImage bufferedImage = new BufferedImage(WIDTH,HEIGHT, BufferedImage.TYPE_INT_ARGB);
        //获得绘图对象
        Graphics graphics = bufferedImage.getGraphics();
        //设置颜色
        graphics.setColor(Color.PINK);
        graphics.setFont(new Font("宋体",Font.PLAIN,FONT_SIZE));
        //绘制线条
        graphics.fillRect(0,0,WIDTH,HEIGHT);
//        graphics.setColor(Color.black);
        graphics.drawRect(30,10,100,40);
        graphics.setColor(Color.BLUE);
        graphics.setPaintMode();
        graphics.drawLine(WIDTH/2,0,WIDTH/2,HEIGHT);
        graphics.drawLine((WIDTH/2)-10,0,(WIDTH/2)-10,HEIGHT);
        graphics.drawLine((WIDTH/2)+10,0,(WIDTH/2)+10,HEIGHT);

        codeStr = new StringBuffer();
        for(int i =0;i<4;i++){
            int index = (int)(Math.random()*str.length);
            codeStr = codeStr.append(str[index]);
        }

        graphics.drawString(codeStr.toString(),0,HEIGHT/2);
        req.getSession().setAttribute("code",codeStr.toString());
        //通过Servlet的输出流，将图片发送给浏览器
        ImageIO.write(bufferedImage,"PNG",resp.getOutputStream());
    }
}
